﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using MindASPCoreWebAPI.BaseLibrary.Tools.LogTools;
using MindASPCoreWebAPI.DtoModel.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace MindASPCoreWebAPI.ApiLibrary.ErrorManager
{
    public class CustomerExceptionMiddleware
    {
        private readonly RequestDelegate _next;

        /// <summary>
        ///构造函数 对下一个中间委托进行挂载
        /// </summary>
        /// <param name="next">下一个中间件的委托</param>
        public CustomerExceptionMiddleware(RequestDelegate next)
        {
            this._next = next;
        }
        /// <summary>
        /// 声明中间件执行的方法,上一个中间件会调用这个方法,在这个方法里可以执行下一个中间件,  .net core会通过反射来执行该方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                Log4Tools.Error("全局错误处理", ex);
                ResultModel<bool> resultModel = new ResultModel<bool>();

                resultModel.code = ResultCode.Error;
                resultModel.mess = $"错误信息是:{ex.ToString()}";

                context.Response.ContentType = "application/problem+json";

                var title = "出现错误 " + ex.Message;
                var details = ex.ToString();



                //Serialize the problem details object to the Response as JSON (using System.Text.Json)
                var stream = context.Response.Body;
                await JsonSerializer.SerializeAsync(stream, resultModel);


            }
        }


    }
    /// <summary>
    /// 编写加载自定义错误处理中间件的扩展方法
    /// </summary>
    public static class ErrorHandlingExtensions
    {
        /// <summary>
        /// 加载自定义全局错误处理中间件方法 IApplicationBuilder 的扩展方法
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseCustomerExceptionMiddleware(this IApplicationBuilder builder)
        {
            //挂载中间件
            return builder.UseMiddleware<CustomerExceptionMiddleware>();
        }
    }
}

